package com.heima.app.gateway.filter;

import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 认证过滤器
 */
@Component
@Slf4j
@Order(-1)//过滤器执行顺序，值越小优先级越高
public class AuthorizeFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.判断是否是登录
        if(request.getURI().toString().contains("/login")){
            //放行
            return chain.filter(exchange);
        }

        //3.获取token
        String token = request.getHeaders().getFirst("token");

        //4.校验token
        if(StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//401一般代表无权限
            return response.setComplete();//直接返回 不在路由到后端微服务
        }
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if(i==1 || i==2){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);//401一般代表无权限
                return response.setComplete();//直接返回 不在路由到后端微服务
            }


            //获得token解析后中的用户信息
            Integer userId = (Integer) claimsBody.get("id");
            //在header中添加新的信息
            ServerHttpRequest serverHttpRequest = request.mutate().header("userId",String.valueOf(userId)).build();
            //重置header
            exchange.mutate().request(serverHttpRequest).build();





        } catch (Exception exception) {
            exception.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//401一般代表无权限
            return response.setComplete();//直接返回 不在路由到后端微服务
        }


        //5.放行
        return chain.filter(exchange);
    }

}
